<?php

namespace App\Http\Controllers\TK_Api;

use App\Http\Requests\Common\NoteStoreRequest;
use App\Models\Note;
use DB;
use Illuminate\Http\JsonResponse;

class NoteController extends ApiBaseController
{

    /**
     * 获取我的笔记
     * @return JsonResponse|object
     */
    public function getMyNote() {
        // 学科分类，题目标题，笔记内容，点赞数量，知识点名称
        $list = null;
        $ids = $this->user->note()->pluck('id');
        if ($ids) {
            $_list = $this->user->note()
                ->join('tiku_questions1', 'notes.questionId',  '=',  'tiku_questions1.id')
                ->join('tiku_knowledge', 'tiku_questions1.thirdKnowledgeId',  '=',  'tiku_knowledge.id')
                ->join('tiku_course', 'tiku_knowledge.courseId',  '=',  'tiku_course.id')
                ->select(['notes.id', 'notes.content', 'notes.like', 'tiku_knowledge.knowledgeName', 'tiku_course.fullName as courseName', 'tiku_questions1.bodyhtml as questionBody', 'tiku_questions1.id as questionId', 'tiku_knowledge.id as knowledgeId', 'tiku_course.id as courseId'])
                ->orderByDesc('notes.created_at')
                ->limit(50)->get();

            $list = [];
            foreach ($_list as $item) {
                $item['questionBody'] = replaceStaticFileUrlInString($item['questionBody']);
                $course = array_column($list, 'courseName');
                $searchResult = array_search($item['courseName'], $course);
                if($searchResult === false) {
                    $list[] = [
                        'courseName' => $item['courseName'],
                        'data' => [$item]
                    ];
                }
                elseif (array_key_exists($searchResult, $course)) {
                    $list[$searchResult]['data'][] = $item;
                }
                else {
                    $list[] = [
                        'courseName' => $item['courseName'],
                        'data' => [$item]
                    ];
                }
            }
        }

        $list = [
            'ids' => $ids ?? [],
            'data' => $list
        ];

        return $this->restful($list);
    }

    /**
     * 发布笔记
     * @param NoteStoreRequest $request
     * @return JsonResponse|object
     */
    public function store(NoteStoreRequest $request) {
        $params = $request->validated();

        $params['userId'] = $this->user->id;
        $note = new Note($params);
        $result = $note->save();
        $data = null;
        if($result) {
            $data = Note::where('notes.id', $note->id)
                ->join('user', 'notes.userId', '=', 'user.id')
                ->leftJoin('user_like_note', function ($join) {
                    $join->on('notes.id', '=', 'user_like_note.noteId')
                        ->where('user.id', '=', isset($this->user) ? $this->user->id : 0);
                })
                ->selectRaw('notes.id, notes.content, notes.created_at, notes.like, user.id as userId, user.avatar, user.nickname, user.username, IF(user_like_note.id IS NULL, false, true) as liked')
                ->first();
        }

        return $this->restful($data);
    }

    /**
     * 删除笔记
     * @param $id
     * @return JsonResponse|object
     */
    public function delete($id) {
        $result = Note::where('id', $id)->where('userId', $this->user->id)->delete();

        return $this->restful($result);
    }

    /**
     * 获取题目下的所有笔记
     * @param $id
     * @return JsonResponse|object
     */
    public function getNoteByQuestionId($id) {
        $list = Note::where('questionId', $id)
            ->join('user', 'notes.userId', '=', 'user.id')
            ->leftJoin('user_like_note', function ($join) {
                $join->on('notes.id', '=', 'user_like_note.noteId')
                    ->where('user_like_note.userId', '=', isset($this->user) ? $this->user->id : 0);
            })
            ->selectRaw('notes.id, notes.content, notes.created_at, notes.like, user.id as userId, user.avatar, user.nickname, user.username, IF(user_like_note.id IS NULL, false, true) as liked')
            ->orderByDesc('notes.created_at')
            ->get();

        return $this->restful($list);
    }

    /**
     * 喜欢/取消喜欢 笔记
     * @param $id
     * @return JsonResponse|object
     */
    public function like($id) {
        $note = Note::find($id);
        if ($note) {
            DB::transaction(function () use ($id, $note) {
                $this->user->likeNote()->toggle($id);
                $count = DB::table('user_like_note')->where('noteId', $id)->count();
                $note->like = $count;
                $note->save();
            });
        }

        return $this->restful();
    }
}
